import * as step from '@flow-step/step-toolkit'
import process from 'process'
import {getParams} from './params'
import {deploy} from './deploy'
import {check} from './check'
import {rollback} from './rollback'
import {confirm} from './confirm'
import {terminate} from './terminate'
import {getSAEClient, Sae} from './sae'

async function runStep(): Promise<void> {
    const params = getParams()
    step.info(`PIPELINE_ID=${params.pipelineID}`)
    step.info(`PIPELINE_NAME=${params.pipelineName}`)
    step.info(`BUILD_NUMBER=${params.buildNumber}`)
    step.info(`WORK_SPACE=${params.workSpace}`)
    step.info(`PROJECT_DIR=${params.projectDir}`)
    step.info(`BUILD_JOB_ID=${params.buildJobID}`)
    step.info(`REGION_ID=${params.regionID}`)

    step.info(`USE_ACR_EE=${params.USE_ACR_EE}`)
    if (params.USE_ACR_EE) {
        step.info(`ACR_EE_ID=${params.ACR_EE_ID}`)
    }
    step.info(`minReadyInstanceType=${params.minReadyInstanceType}`)
    step.info(`enableGreyTagRoute=${params.enableGreyTagRoute}`)
    step.info(`waitTimeInBatch=${params.waitTimeInBatch}`)

    const saeClient = await getSAEClient()
    const sae = new Sae(saeClient)

    const command = process.env["COMMAND"] as string
    switch (command) {
        case 'RUN':
            await deploy(params,sae);
            break;
        case 'CHECK':
            await check(params,sae);
            break;
        case 'CONFIRM':
            await confirm(params,sae);
            break;
        case 'ROLLBACK':
            await rollback(params,sae);
            break;
        case 'TERMINATE':
            await terminate(params,sae);
            break;
        default:
            step.info('Invalid action. Please provide \'RUN\', \'CHECK\', \'CONFIRM\', \'ROLLBACK\' or \'TERMINATE\'.')
    }

}

runStep()
    .then(function() {
        step.success('run step successfully!')
    })
    .catch(function(err: Error) {
        step.error(err.message)
        process.exit(-1)
    })
